package com.jzr.open.auth;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by Shuangyao
 * 22:50 2018/9/2
 */
@Service("authenticationFailHandler")
public class AuthenticationFailHandler extends SimpleUrlAuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        //this.returnJson(response,e);
        //response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
        //response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setStatus((Integer)request.getAttribute("vStatus"));
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        //int code = HttpServletResponse.SC_FORBIDDEN;
        int code = (Integer)request.getAttribute("vStatus");
        String msg = (String)request.getAttribute("vMessage");
//        if (e instanceof UsernameNotFoundException || e instanceof BadCredentialsException) {
//            msg = "用户名或密码输入错误，登录失败!";
//        } else if (e instanceof DisabledException) {
//            msg = "账户被禁用，登录失败，请联系管理员!";
//        } else {
//            msg = "登录失败!";
//        }
        out.write("{\"code\":" + code + ",\"status\":" + code + ",\"msg\":\"" + msg + "\"" + ",\"message\":\"" + msg + "\"}");
        out.flush();
        out.close();
    }

    private void returnJson(HttpServletResponse response,
                            AuthenticationException exception) throws IOException {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println("{\"exceptionId\":\"null\",\"code\":401,\"status\":401" +
                ",\"message\": \""+ exception.getMessage()+"\""+
                ",\"msg\": \""+ exception.getMessage()+"\""+
                ",\"serverTime\": " + System.currentTimeMillis() + "}");
    }
}
